package com.sahyadri.web.util.service.adpater;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;

import com.sahyadri.web.bean.User;
import com.sahyadri.web.util.exception.AuthenticationException;
import com.sahyadri.web.util.exception.UserManagementException;

public class UserDetailsServiceImpl implements UserDetailsService{
	
	private static final Log log= LogFactory.getLog(UserDetailsServiceImpl.class);
	private static String rolePrefix = "ROLE_";

	public UserDetailsServiceImpl() {
		super();
	}

	@Autowired
	private UserService userService;
	
	
	@Autowired
	private AuthenticationServiceAdapter authenticationServiceAdapter;

	public AuthenticationServiceAdapter getAuthenticationServiceAdapter() {
		return authenticationServiceAdapter;
	}

	public void setAuthenticationServiceAdapter(
			AuthenticationServiceAdapter authenticationServiceAdapter) {
		this.authenticationServiceAdapter = authenticationServiceAdapter;
	}
   	  	
	@Override
	public User getUser(String userName, String password) throws AuthenticationException, UserManagementException {
		boolean authenticated = this.authenticationServiceAdapter.authenticate(userName, password);
		if(!authenticated){
			throw new AuthenticationException("Failed to authenticate user: "+userName);
		}
		User user = null;
		try {
			user = userService.getUserByUserName(userName);
		}catch(Exception e) {
			log.error("error in getUserByUserName " +e);
		}
		log.debug("User Roles: " + user.getRole().getRoleCd());
		user.setUsername(userName);
		user.setAuthorities(AuthorityUtils.createAuthorityList(rolePrefix+user.getRole().getRoleCd()));
		log.debug("User Roles: " + user.getAuthorities());
		return user;
	}
	
	
	@Override
	public User getUser(String loginId) {

		
		return new User();

	}

	

	

}
